#include "quickFindSet.h"
QuickFindSet *creteQuickFindSet(int n) {
    QuickFindSet *setQF = (QuickFindSet *) malloc(sizeof (QuickFindSet));
    setQF->groupID = (int *) malloc(sizeof (int) *n);
    setQF->data = (Element *) malloc(sizeof (Element) *n);
    setQF->n = n;
    return setQF;
}

void releaseQuickFindSet(QuickFindSet *setQF) {
    if (setQF) {
        if (setQF->data) {
            free(setQF->data);
            setQF->data = NULL;
        } if(setQF->groupID) {
            free(setQF->groupID);
            setQF->groupID = NULL;
        }
    }
    free(setQF);
}

void initQuickFindSet(QuickFindSet *setQF,const Element *data,int n) {
    for(int i = 0; i < n;i++) {
        setQF->data[i] = data[i];
        setQF->groupID[i] = i;
    }
}

static int findIndex(QuickFindSet *setQF, Element e) {
    for(int i = 0;i < setQF->n; ++i) {
        if (setQF->data[i] == e) {
            return i;
        }
    }
    return -1;
}

int isSameQF(QuickFindSet *setQF,Element a,Element b) {
    int aIndex = findIndex(setQF,a);
    int bIndex = findIndex(setQF,b);
    if (aIndex == -1|| bIndex == -1) {
        return 0;
    }
    return setQF->groupID[aIndex]  == setQF->groupID[bIndex];
}

void unionQF(QuickFindSet *setQF,Element a,Element b) {
    int aIndex = findIndex(setQF,a);
    int bIndex = findIndex(setQF,b);
    for (int i = 0; i < setQF->n; ++i) {
        if (setQF->groupID[i] == aIndex) {
            setQF->groupID[i] = bIndex;
        }
    }
}